package com.example.dbg.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.dbg.common.utils.FilterParamUtil;
import com.example.dbg.model.po.CuUser;
import com.example.dbg.service.ICuUserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @user DBG_ZXX
 * @date 2018/10/27 17:59
 * @desc
 **/
@Controller
public class LoginController {

    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    ICuUserService cuUserService;

    /**
     * @desc: 登录页面
     * @param request
     * @retrun:  java.lang.String
     * @Date:    2018/10/28 16:54
     */
    @RequestMapping(value = "login" , method = RequestMethod.GET)
    public String login(HttpServletRequest request){

        Map map = FilterParamUtil.getParameterMap(request,true);
        map.forEach((k,v) -> System.out.println(k + "=" + v));
        logger.info(">>>>>登录页面");
        return "login";
    }

    /**
     * @desc: 登录
     * @param request
     * @param model
     * @retrun:  java.lang.String
     * @Date:    2018/10/28 13:12
     */
    @RequestMapping(value = "loginIn" , method = RequestMethod.POST)
    public String toLogin(HttpServletRequest request , HttpServletResponse response, Model model){
        Map map = FilterParamUtil.getParameterMap(request,true);
        map.forEach((k,v) -> System.out.println(k + "=" + v));
        if (StringUtils.checkValNull(map.get("loginName")) || StringUtils.checkValNull(map.get("loginPwd"))){
            model.addAttribute("msg" , "用户以及密码不能为空!") ;
            return "/login";
        }else {
            String loginName = map.get("loginName").toString();
            String loginPwd = map.get("loginPwd").toString();
            CuUser cuUser = cuUserService.login(loginName, loginPwd);
            if (StringUtils.checkValNotNull(cuUser)) {
                HttpSession session = request.getSession();
                session.setAttribute("loginName", cuUser.getLoginName());
                session.setAttribute("cuUserId", cuUser.getId());
                System.out.println("登录成功！");
                return "redirect:pwd/pwdList/" + cuUser.getId();
            } else {
                model.addAttribute("msg", "用户或者密码错误");
                return "/login";
            }
        }
    }

}
